package org.swimv2.servlets;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swimv2.entities.Job;
import org.swimv2.interfaces.JobsManagerRemote;
import org.swimv2.utils.ContextUtil;

/**
 * Servlet implementation class JobServlet
 */
public class JobServlet extends HttpServlet {
	
	private static final long serialVersionUID = 4831886158599836262L;
	
	private Job  j = null;
	private JobsManagerRemote mgr_j = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JobServlet() {
        super();
    }

	/**
	 * Visualizza un certo {@link Job}.
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		try {
			Context ctx = ContextUtil.getInitialContext();
			mgr_j = (JobsManagerRemote) ctx.lookup("JobsManagerJNDI");
			
			j = mgr_j.getJob( Integer.parseInt(request.getParameter("job_id")) );
			
			RequestDispatcher disp;
			disp = request.getRequestDispatcher("app/job.jsp");
			
			/* Lavoro da visualizzare trovato */
			if (j != null) {
				request.setAttribute("page_job", j);
			/* Lavoro non trovato */
			} else {
				request.setAttribute("error_message", "Errore: lavoro non trovato");
			}
			// Effettua il redirect
			disp.forward(request, response);
		}
		catch (NamingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
